import React, {useEffect, useState} from 'react';
import axios from 'axios'
import {Link} from "react-router-dom";
import LoadingSpinner from "../components/LoadingSpinner";
import InlineError from "../components/InlineError";
import * as errmsg from '../constants'

export default function Popular() {
    const [loading, setLoading] = useState(true);
    const [posts, setPosts] = useState([])
    const [error, setError] = useState('')

    useEffect(() => {
        axios.get('/api/v1/posts/popular/')
            .then(response => {
                setLoading(false)
                setPosts(response.data.results)
                setError('')
            })
            .catch(err => {
                setLoading(false)
                setPosts([])
                setError(errmsg.CUSTOM_ERROR_MSG)
            })
    }, [])

    const postList = (
        posts.map(post => (
            <li key={post.slug}>
                <Link to={`/post/${post.slug}`} className="link-dark">
                    {post.slug}
                </Link>
                 <small className="text-muted ms-2">
                        阅读: {post.num_views}
                </small>
            </li>
        ))
    )

    if (loading) return <LoadingSpinner/>
    if (error) return <InlineError error={error}/>

    return (
        <div className="px-4 mb-3">
            <h4 className="border-bottom mb-3">推荐阅读</h4>
            <ol className="list-unstyled mb-0">
                {postList}
            </ol>
        </div>
    )
};
